﻿/**
 * 
 *
 * @author  Wemerson Januario (ExtJS 3.x)
 * @license LGPLv3 http://www.opensource.org/licenses/lgpl-3.0.html
 * @version 1.0 beta, 07/12/2008 - ExtJS 2.x
 * @version 1.0, 05/03/2009 - ExtJS 3.x
 * @version 1.1, 07/18/2009 - ExtJS 3.x
 * @version 1.6, 16/06/2010 - ExtJS 3.2.1 ++
 */

Ext.namespace('Ext.ux');

/**
 * Construtor
 *
 * @param {Object} config
 * @extends {Ext.util.Observable}
 */
Ext.ux.LoginWindow = function (config) {
    Ext.apply(this, config);

    // Css usado para criar a janela
    var css = "#login-logo .x-plain-body {background:#f9f9f9 url('" + this.basePath + "/" + this.winBanner + "') no-repeat;}" + "#login-form  {background: " + this.formBgcolor + " none;}" + ".ux-auth-header-icon {background: url('" + this.basePath + "/locked.gif') 0 4px no-repeat !important;}" + ".ux-auth-form {padding:10px;}" + ".ux-auth-login {background-image: url('" + this.basePath + "/key.gif') !important}" + ".ux-auth-close {background-image: url('" + this.basePath + "/close.gif') !important}";

    Ext.util.CSS.createStyleSheet(css, this._cssId);

    if (this.forceVirtualKeyboard) {
        this.enableVirtualKeyboard = true;
    }

    // Eventos
    this.addEvents({
        'show': true,
        'reset': true,
        'success': true,
        'failure': true,
        'submit': true,
        'submitpass': true
    });
    Ext.ux.LoginWindow.superclass.constructor.call(this, config);

    //Painel topo (Logotipo do sistema)
    this._logoPanel = new Ext.Panel({
        baseCls: 'x-plain',
        id: 'login-logo',
        region: 'center'
    });

    // Seta id para o elementos
    this._usernameId = Ext.id();
    this._passwordId = Ext.id();
    this._rememberMeId = Ext.id();
    this._emailId = Ext.id();
    this._recoverFieldsetId = Ext.id();
    this._RecoverUsernameId = Ext.id();
    this._languageId = Ext.id();
    this._loginButtonId = Ext.id();
    this._resetButtonId = Ext.id();
    this._passwordButtonId = Ext.id();
    this._winPasswordButtonId = Ext.id();

    this.cp = new Ext.state.CookieProvider({
        expires: new Date(new Date().getTime()+(1000*60*60*24*30)) //30 dias
    });
   
    Ext.state.Manager.setProvider(this.cp);

    // form panel
    this._formPanel = new Ext.form.FormPanel({
        region: 'south',
        border: false,
        bodyStyle: "padding: 10px;",
        waitMsgTarget: true,
        id: 'login-form',
        baseCls: 'x-plain',
        labelWidth: 80,
        defaults: {
            width: 300
        },
        baseParams: {
            task: 'login'
        }, 
        height: 130,
        items: [{
            xtype: 'textfield',
            id: this._usernameId,
            name: this.usernameField,
            emptyText: 'Seu login',
            fieldLabel: this.usernameLabel,
            vtype: this.usernameVtype,
            validateOnBlur: false,
            maxLength : 11,
            allowBlank: false
        },
        {
            xtype: 'textfield',
            inputType: 'password',
            id: this._passwordId,
            name: this.passwordField,
            fieldLabel: this.passwordLabel,
            vtype: this.passwordVtype,
            width: this.enableVirtualKeyboard == true ? 280 : 300,
            validateOnBlur: false,
            allowBlank: false,
            validationEvent: this.forceVirtualKeyboard == true ? 'blur' : 'keyup',
            enableKeyEvents: true,
            keyboardConfig: {
                showIcon: true,
                languageSelection: true
            },
            plugins: this.enableVirtualKeyboard == true ? new Ext.ux.plugins.VirtualKeyboard() : null,
            listeners: {
                render: function () {
                    this.capsWarningTooltip = new Ext.ToolTip({
                        target: this.id,
                        anchor: 'top',
                        width: 305,
                        html: '<div class="ux-auth-warning">Caps Lock está ativado</div><br />' +
                    '<div>Atenção, com a tecla Caps Lock ativada voce pode digitar a senha incorreta.</div><br />' +
                    '<div>Desative a tecla Caps Lock antes de digitar a sua senha.</div>'
                    });

                    // disable to tooltip from showing on mouseover
                    this.capsWarningTooltip.disable();

                    // When the password field fires the blur event,
                    // the tootip gets enabled automatically (possibly an ExtJS bug).
                    // Disable the tooltip everytime it gets enabled
                    // The tooltip is shown explicitly by calling show()
                    // and enabling/disabling does not affect the show() function.
                    this.capsWarningTooltip.on('enable', function () {
                        this.disable();
                    });
                },

                keypress: {
                    fn: function (field, e) {
                        if (this.forceVirtualKeyboard) {
                            field.plugins.expand();
                            e.stopEvent();
                        }
                        else {
                            var charCode = e.getCharCode();
                            if ((e.shiftKey && charCode >= 97 && charCode <= 122) || (!e.shiftKey && charCode >= 65 && charCode <= 90)) {

                                field.capsWarningTooltip.show();
                            }
                            else {
                                if (field.capsWarningTooltip.hidden == false) {
                                    field.capsWarningTooltip.hide();
                                }
                            }
                        }
                    },
                    scope: this
                },

                blur: function (field) {
                    if (this.capsWarningTooltip.hidden == false) {
                        this.capsWarningTooltip.hide();
                    }
                }
            }
        },
        {
            xtype: 'iconcombo',
            id: this._languageId,
            hiddenName: this.languageField,
            fieldLabel: this.languageLabel,
            store: new Ext.data.SimpleStore({
                fields: ['languageCode', 'languageName', 'countryFlag'],
                data: [
                ['pt_BR', 'Portuguese - Brazil', 'ux-flag-br'],
                ['es', 'Spanish - Spain', 'ux-flag-es'],
//                ['frfr', 'French - France', 'ux-flag-fr'],
//                ['itit', 'Italian - Italy', 'ux-flag-it'],
                ['en', 'English - The United States', 'ux-flag-us']]
            }),
            valueField: 'languageCode',
            value: this.defaultLanguage,
            displayField: 'languageName',
            iconClsField: 'countryFlag',
            triggerAction: 'all',
            editable: false,
            mode: 'local'
        }, {
            xtype       : 'checkbox',
            id          : this._rememberMeId,
            name        : this.rememberMeField,
            boxLabel    : '&nbsp;' + this.rememberMeLabel,
            listeners: {
                render: function() {
                    Ext.get(Ext.DomQuery.select('#x-form-el-' + this._rememberMeId + ' input')).set({
                        qtip: 'Não recomendado para computadores compartilhados.'
                    });
                },
                check: function(){
                    if(Ext.getCmp(this._rememberMeId).getValue() == true){
                        Ext.state.Manager.set('username', Ext.getCmp(this._usernameId).getValue());
                    }else{
                        Ext.state.Manager.clear('username');
                    }
                },
                scope: this
            }
        }]
    });
    Ext.getCmp(this._languageId).on('select', function () {
        this.defaultLanguage = Ext.getCmp(this._languageId).getValue();
        this.setlanguage();
    },
    this);
    //Painel do formulário de recuperação de senha
    this._formPasswordPanel = new Ext.form.FormPanel({
        bodyStyle: "padding: 5px;",
        id: 'password-form',
        waitMsgTarget: true,
        labelWidth: 80,
        autoHeight: true,
        buttonAlign: 'center',
        baseParams: {
            task: 'forgotPassword'
        },
        items: [{
            layout: 'form',
            border: false,
            items: [{
                xtype: 'fieldset',
                title: this.recoverFieldset,
                id: this._recoverFieldsetId,
                autoHeight: true,
                items: [{
                    xtype: 'textfield',
                    id: this._RecoverUsernameId,
                    name: this.RecoverUsernameField,
                    fieldLabel: this.RecorverUsernameLabel,
                    vtype: this.RecoverUsernameVtype,
                    validateOnBlur: false,
                    maxLength : 11,
                    allowBlank: false
                },{
                    xtype: 'textfield',
                    vtype: this.emailVtype,
                    id: this._emailId,
                    name: this.emailField,
                    fieldLabel: this.emailLabel,
                    validateOnBlur: false,
                    anchor: '98%',
                    allowBlank: false
                }]
            }]
        }],
        buttons: [{
            text: this.passwordButton,
            id: this._winPasswordButtonId,
            width: 100,
            handler: this.Passwordsubmit,
            scale: 'medium',
            scope: this
        }]
    });

    // botões padroes
    var buttons = [{
        id: this._loginButtonId,
        text: this.loginButton,
        handler: this.submit,
        scale: 'medium',
        scope: this
    }];
    var keys = [{
        key: [10, 13],
        handler: this.submit,
        scope: this
    }];
    if (typeof this.passwordButton == 'string') {
        buttons.push({
            id: this._passwordButtonId,
            text: this.passwordButton,
            handler: this.password,
            scale: 'medium',
            scope: this
        });
    }
    if (typeof this.resetButton == 'string') {
        buttons.push({
            id: this._resetButtonId,
            text: this.resetButton,
            //iconCls : 'ux-auth-cslose',
            handler: this.reset,
            scale: 'medium',
            scope: this
        });
    /**keys.push({
            key     : [27],
            handler : this.reset,
            scope   : this
        });**/
    }

    // cria a  window
    this._window = new Ext.Window({
        width: 429,
        height: 300,
        closable: false,
        resizable: false,
        draggable: true,
        modal: this.modal,
        iconCls: 'ux-auth-header-icon',
        title: this.title,
        layout: 'border',
        bodyStyle: 'padding:5px;',
        buttons: buttons,
        buttonAlign: 'center',
        keys: keys,
        plain: false,
        items: [this._logoPanel, this._formPanel]
    });

    // and fire "show" event
    this._window.on('show', function () {
        this.setlanguage();
        Ext.getCmp(this._passwordId).setRawValue('');
        this.fireEvent('show', this);

    },
    this);

    //Cria a janela de recuperação de senha
    this._windowPassword = new Ext.Window({
        width: 400,
        height: 220,
        closable: true,
        resizable: false,
        draggable: true,
        modal: this.modal,
        iconCls: 'ux-auth-header-icon',
        title: this.Passwordtitle,
        bodyStyle: 'padding:5px;',
        keys: keys,
        closeAction: 'hide',
        items: this._formPasswordPanel
    });

    this._windowPassword.on('show', function () {
        this._formPasswordPanel.getForm().reset();
    },
    this);
};

// Extend the Observable class
Ext.extend(Ext.ux.LoginWindow, Ext.util.Observable, {

    /**
     * LoginDialog window title
     *
     * @type {String}
     */
    title: '',

    /**
     * Alert title
     *
     * @type {String}
     */
    sucesso: '',

    /**
     * Alert title
     *
     * @type {String}
     */
    falha: '',

    /**
     * Título da janela de recuperação de senha
     *
     * @type {String}
     */
    Passwordtitle: '',
    /**
     * Título do fieldset da janela de recuperação de senha
     *
     * @type {String}
     */
    recoverFieldset: '',
    /**
     * Mensagem de espera ao enviar os dados
     *
     * @type {String}
     */
    waitMessage: '',

    /**
     * The login button text
     *
     * @type {String}
     */
    loginButton: '',

    /**
     * Texto do botão de recuperação de senha
     *
     * @type {String}
     */
    passwordButton: '',
    /**
     * Reset button
     *
     * @type {String}
     */
    resetButton: '',

    /**
     * Username field label
     *
     * @type {String}
     */
    usernameLabel: '',

    /**
     * Username field name
     *
     * @type {String}
     */
    usernameField: 'username',

    /**
     * Username validation
     *
     * @type {String}
     */
    usernameVtype: 'alphanum',

    /**
     * Password field label
     *
     * @type {String}
     */
    passwordLabel: ' ',

    /**
     * Password field name
     *
     * @type {String}
     */
    passwordField: 'password',

    /**
     * Password field validation
     *
     * @type {String}
     */
    passwordVtype: 'alphanum',
    /**
     * Título do campo email
     *
     * @type {String}
     */
    emailLabel: '',
    /**
     * Nome do campo email
     *
     * @type {String}
     */
    emailField: 'email',

    /**
     * Validação do campo email
     *
     * @type {String}
     */
    emailVtype: 'email',
    
    /**
     * Título do campo email
     *
     * @type {String}
     */
    RecorverUsernameLabel: '',

    /**
     * Nome do campo email
     *
     * @type {String}
     */
    RecoverUsernameField: 'username',

    /**
     * Validação do campo email
     *
     * @type {String}
     */
    RecoverUsernameVtype: 'alphanum',

    /**
     * Language field label
     *
     * @type {String}
     */
    languageLabel: '',

    /**
     * Language field name
     *
     * @type {String}
     */
    languageField: 'lang',

    /**
     * RememberMe field label
     *
     * @type {String}
     */
    rememberMeLabel : 'Lembrar usuário nesse computador ?',

    /**
     * RememberMe field name
     *
     * @type {String}
     */
    rememberMeField : 'rememberme',

    /**
     * Tooltip not Recommended
     *
     * @type {String}
     */
    notRecommended: 'Não recomendado para computadores compartilhados.',
    
    
    /**
     * Enable Virtual Keyboard for password
     *
     * @type {Bool}
     */
    enableVirtualKeyboard: false,

    /**
     * Force Virtual Keyboard for password entry
     * If true, also sets enableVirtualKeyboard property to true
     *
     * @type {Bool}
     */
    forceVirtualKeyboard: false,

    /**
     * encrypt password using md5 and sha1
     *
     * @type {Bool}
     */
    encryptType: 'md5',

    /**
     * Salt prepended to password, before encryption
     * If encrypt property is false, salt is not used
     *
     * @type {String}
     */
    salt: '',

    /**
     * Request url
     *
     * @type {String}
     */
    url: '',
    /**
     * Url de requisição de recuperação de senha
     *
     * @type {String}
     */
    emailUrl: '',
    /**
     * Url de destino caso login seja efetivado
     *
     * @type {String}
     */
    locationUrl: '',

    /**
     * Path to images
     *
     * @type {String}
     */
    basePath: '',
    /**
     * Logotipo do sistema (Banner)
     *
     * @type {String}
     */
    winBanner: '',
    /**
     * Cor de fundo do formulário
     *
     * @type {String}
     */
    formBgcolor: '',
    /**
     * Idioma padrão do formulário
     */
    defaultLanguage: 'pt_BR',

    /**
     * Form submit method
     *
     * @type {String}
     */
    method: 'post',

    /**
     * Open modal window
     *
     * @type {Bool}
     */
    modal: false,

    /**
     * CSS identifier
     *
     * @type {String}
     */
    _cssId: 'ux-LoginWindow-css',

    /**
     * Head info panel
     *
     * @type {Ext.Panel}
     */
    _logoPanel: null,

    /**
     * Form panel
     *
     * @type {Ext.form.FormPanel}
     */
    _formPanel: null,

    /**
     * The window object
     *
     * @type {Ext.Window}
     */
    _window: null,
    /**
     * Objeto da janela de recuperação de senha
     *
     * @type {Ext.Window}
     */
    _windowPassword: null,

    /**
     * Show the LoginDialog
     *
     * @param {Ext.Element} el
     */
    show: function (el) {
        this._window.show(el);
        if(Ext.state.Manager.get('username')){
            Ext.getCmp(this._usernameId).setValue(Ext.state.Manager.get('username'));
        }else{
            Ext.getCmp(this._usernameId).emptyText = 'Login';
        }
        
    },
    /**
     * Exibe a  janela de recuperação de senha
     *
     * @param {Ext.Element} el
     */
    password: function (el) {
        this._windowPassword.show(el);
    },
    /**
     * Limpa o formulário
     */
    reset: function () {
        if (this.fireEvent('reset', this)) {
            this._formPanel.getForm().reset();
            this.defaultLanguage = Ext.getCmp(this._languageId).getValue();
            this.setlanguage();
        }
    },

    /**
     * Seleciona o idioma
     */
    setlanguage: function () {
        Ext.override(Ext.form.Field, {
            setFieldLabel: function (text) {
                if (this.rendered) {
                    this.el.up('.x-form-item', 10, true).child('.x-form-item-label').update(text);
                } else {
                    this.fieldLabel = text;
                }
            }
        });
        if (this.defaultLanguage == 'pt_BR') {
            this._window.setTitle('Autenticação');
            this._windowPassword.setTitle('Recuperar senha');
            Ext.getCmp(this._loginButtonId).setText('Entrar');
            Ext.getCmp(this._passwordButtonId).setText('Recuperar senha');
            Ext.getCmp(this._resetButtonId).setText('Limpar');
            Ext.getCmp(this._winPasswordButtonId).setText('Recuperar senha');
            Ext.getCmp(this._emailId).setFieldLabel('Email');
            Ext.getCmp(this._RecoverUsernameId).setFieldLabel('Usuário (CPF)');
            Ext.getCmp(this._recoverFieldsetId).setTitle('Digite seu usu�rio e email');
            Ext.getCmp(this._usernameId).setFieldLabel('Usuário:');
            Ext.getCmp(this._passwordId).setFieldLabel('Senha:');
            Ext.getCmp(this._languageId).setFieldLabel('Idioma:');
            this.waitMessage = 'Enviando dados...';
            this.sucesso = 'Sucesso';
            this.falha = 'Falha';
        } else if (this.defaultLanguage == 'es') {
            this._window.setTitle('Autenticación');
            this._windowPassword.setTitle('Recuperar Contraseña');
            Ext.getCmp(this._loginButtonId).setText('Inicio');
            Ext.getCmp(this._passwordButtonId).setText('Recuperar Contraseña');
            Ext.getCmp(this._resetButtonId).setText('Limpiar');
            Ext.getCmp(this._winPasswordButtonId).setText('Recuperar Contraseña');
            Ext.getCmp(this._emailId).setFieldLabel('Email');
            Ext.getCmp(this._RecoverUsernameId).setFieldLabel('Usuario');
            Ext.getCmp(this._recoverFieldsetId).setTitle('Ingrese su usuario y e-mail');
            Ext.getCmp(this._usernameId).setFieldLabel('Usuario:');
            Ext.getCmp(this._passwordId).setFieldLabel('Contraseña:');
            Ext.getCmp(this._languageId).setFieldLabel('Idioma:');
            this.waitMessage = 'Envío de datos...';
            this.sucesso = 'Éxito';
            this.falha = 'Fracaso';
        } else if (this.defaultLanguage == 'en') {
            this._window.setTitle('Authentication');
            this._windowPassword.setTitle('Recover password');
            Ext.getCmp(this._loginButtonId).setText('Login');
            Ext.getCmp(this._passwordButtonId).setText('Recover password');
            Ext.getCmp(this._resetButtonId).setText('Clear');
            Ext.getCmp(this._winPasswordButtonId).setText('Recover password');
            Ext.getCmp(this._emailId).setFieldLabel('Email');
            Ext.getCmp(this._RecoverUsernameId).setFieldLabel('Username');
            Ext.getCmp(this._recoverFieldsetId).setTitle('Enter your username and email');
            Ext.getCmp(this._usernameId).setFieldLabel('Username:');
            Ext.getCmp(this._passwordId).setFieldLabel('Password:');
            Ext.getCmp(this._languageId).setFieldLabel('Language:');
            this.waitMessage = 'Sending data...';
            this.sucesso = 'Success';
            this.falha = 'Failure';
        }
    },

    /**
     * Hide and cleanup the LoginWindow
     */
    destroy: function () {
        this._window.hide();
        this.purgeListeners();
        Ext.util.CSS.removeStyleSheet(this._cssId);
        var self = this;
        delete self;
    },

    /**
     * Submit login details to the server
     */
    submit: function () {
        var form = this._formPanel.getForm();

        if (form.isValid()) {
            Ext.getCmp(this._loginButtonId).disable();
            if (Ext.getCmp(this._resetButtonId)) {
                Ext.getCmp(this._resetButtonId).disable();
            }
            if (Ext.getCmp(this._passwordButtonId)) {
                Ext.getCmp(this._passwordButtonId).disable();
            }
            if (this.encryptType == 'md5') {
                Ext.getCmp(this._passwordId).setRawValue(
                    Ext.util.MD5(Ext.getCmp(this._passwordId).getValue()));
            } else if(this.encryptType == 'sha1') {
                Ext.getCmp(this._passwordId).setRawValue(
                    Ext.ux.Crypto.SHA1.hash(this.salt + Ext.getCmp(this._passwordId).getValue()));
            }

            if (this.fireEvent('submit', this, form.getValues())) {
                form.submit({
                    url: this.url,
                    method: this.method,
                    waitMsg: this.waitMessage,
                    success: this.onSuccess,
                    failure: this.onFailure,
                    scope: this
                });
            }
        }
    },
    /**
     * Envia a requisição de recuperação de senha
     */
    Passwordsubmit: function () {
        var form = this._formPasswordPanel.getForm();

        if (form.isValid()) {
            Ext.getCmp(this._winPasswordButtonId).disable();
            if (this.fireEvent('submitpass', this, form.getValues())) {
                form.submit({
                    url: this.emailUrl,
                    method: this.method,
                    waitMsg: this.waitMessage,
                    success: this.onEmailSuccess,
                    failure: this.onEmailFailure,
                    scope: this
                });
            }
        }
    },

    /**
     * On success
     *
     * @param {Ext.form.BasicForm} form
     * @param {Ext.form.Action} action
     */
    onSuccess: function (form, action) {
        if (action && action.result) {
            semx= window.open(this.locationUrl,"main","toolbar=no,location=no,status=no,resizable=no,scrollbars=yes,menubar=no,fullscreen=1");
        // semx.focus();
        //  semx.resizeTo(410,250);
        //  semx.moveTo(180,200);
        // semx.location= this.locationUrl;

        }
        Ext.getCmp(this._loginButtonId).enable();
        if (Ext.getCmp(this._resetButtonId)) {
            Ext.getCmp(this._resetButtonId).enable();
        }
        if (Ext.getCmp(this._passwordButtonId)) {
            Ext.getCmp(this._passwordButtonId).enable();
        }
		
		
    },


    /**
     * On failures
     *
     * @param {Ext.form.BasicForm} form
     * @param {Ext.form.Action} action
     */
    onFailure: function (form, action) {
        // enable buttons
        Ext.getCmp(this._loginButtonId).enable();
        if (Ext.getCmp(this._resetButtonId)) {
            Ext.getCmp(this._resetButtonId).enable();
        }
        if (Ext.getCmp(this._passwordButtonId)) {
            Ext.getCmp(this._passwordButtonId).enable();
        }
        if (this.encrypt) {
            Ext.getCmp(this._passwordId).setRawValue('');
        }

        Ext.getCmp(this._passwordId).focus(true);

    },
    /**
     * Se receber sucesso
     *
     * @param {Ext.form.BasicForm} form
     * @param {Ext.form.Action} action
     */
    onEmailSuccess: function (form, action) {
        Ext.getCmp(this._winPasswordButtonId).enable();
        if (action && action.result.msg) {
            Ext.MessageBox.alert(this.sucesso, action.result.msg, this._windowPassword.hide());
        }
        

    },
    /**
     * Se receber falha
     *
     * @param {Ext.form.BasicForm} form
     * @param {Ext.form.Action} action
     */
    onEmailFailure: function (form, action) {
        // Ativa os bot�es
        Ext.getCmp(this._winPasswordButtonId).enable();
        if (action && action.result.msg) {
            Ext.MessageBox.alert(this.falha, action.result.msg);
        }
        
    }

});